package com.xlkj.receiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.widget.Toast;

import com.xlkj.SxxlkjApplication;
import com.xlkj.faces_input.MainActivity;

/**
 * 自定义异常处理类
 * <p>
 * Created by Mouzhai on 2017/4/11.
 */

public class ExceptionHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG="ExceptionHandler";

    private Context context;
    private Thread.UncaughtExceptionHandler mUncaughtExceptionHandler;
    private SxxlkjApplication sxxlkjApplication;

    public ExceptionHandler(Context context) {
        this.context = context;
        mUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();// 获取系统默认的异常处理类
        sxxlkjApplication = new SxxlkjApplication();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mUncaughtExceptionHandler != null) {
            // 若是用户没有设置异常处理，则让系统默认的类来处理异常
            mUncaughtExceptionHandler.uncaughtException(thread, ex);
        } else {
            // 进行自定义的方法
            // 设置定时任务，1秒后重启此 App
            Intent intent = new Intent(context, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent restartIntent = PendingIntent.getActivity(context, 0, intent, 0);
            AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);
            // 移除当前任务
            sxxlkjApplication.finishActivity();
        }
    }

    /**
     * 对于抛出的异常进行处理，例如打印日志、发送文件给服务器等等
     *
     * @param ex 导致崩溃的异常
     * @return 若在此处理了异常，则返回 true，否则返回 false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        // 此处可以进行一些更为复杂的请求，例如打印崩溃信息日志等
        // 这里弹出提示信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, "很抱歉，程序崩溃了,一秒钟后重启。", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();
        return true;
    }
}